﻿using System;
using System.Data;
using System.Data.Common;

namespace ShopB2C.DBUtilities {
    /// <summary>
    /// 数据库操作抽象基类
    /// <remarks>
    /// MatchZhou - 2009/1/20
    /// </remarks>
    /// </summary>
    public abstract class DbBase {
        /// <summary>
        /// 连接字符串
        /// </summary>
        public static string ConnectionString { get; set; }
        /// <summary>
        /// 组合参数
        /// </summary>
        /// <param name="cmd">command对象</param>
        /// <param name="dbParams">参数组</param>
        protected static void PrepareCommand(DbCommand cmd, params DbParameter[] dbParams) {
            if (!object.Equals(dbParams, null)) {
                foreach (DbParameter parm in dbParams) {
                    if (!object.Equals(parm, null)) {
                        if ((parm.Direction == ParameterDirection.Input || parm.Direction == ParameterDirection.InputOutput) &&  object.Equals(parm.Value, null)) {
                            parm.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(parm);
                    }
                }
            }
        }
        /// <summary>
        /// 返回存储过程、内置函数或用户定义函数之类的操作的返回值
        /// </summary>
        /// <typeparam name="T">返回的参数类型</typeparam>
        /// <param name="cmd">command对象</param>
        /// <param name="defaultValue">缺省值</param>
        /// <returns>指定的参数类型，为 null 时返回指定的缺省值</returns>
        protected static T GetReturnValue<T>(DbCommand cmd, T defaultValue) {
            if (!object.Equals(cmd, null)) {
                foreach (DbParameter parm in cmd.Parameters) {
                    if (parm.Direction == ParameterDirection.ReturnValue) {
                        return object.Equals(parm.Value, null)
                                ? defaultValue
                                : (T)Convert.ChangeType(parm.Value, typeof(T));
                    }
                }
            }
            return defaultValue;
        }
    }
}
